package com.lagou.util;

import com.lagou.ServerBootstrap;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomerDataSource {

    private static ZkClient zkClient = ServerBootstrap.zkClient;
    private static Map<String,String> configMap = new HashMap<>();
    private static ThreadLocal<ComboPooledDataSource> threadLocal = new ThreadLocal();

    private static final String config_path = "/config";

    public static Connection getConnection(){
        if(threadLocal.get()!=null){
            try {
                return threadLocal.get().getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void init() throws PropertyVetoException {
        getConfig();
        initDataSource();
        startListener();
    }

    private static void getConfig() {
        List<String> children = zkClient.getChildren(config_path);
        for (String child : children) {
            String data = zkClient.readData(config_path+"/"+child).toString();
            System.out.println(child+"======>"+data);
            configMap.put(child,data);
        }
    }
    //driverClassName, password, url, username
    private static void initDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(configMap.get("driverClassName"));
        dataSource.setJdbcUrl(configMap.get("url"));
        dataSource.setUser(configMap.get("username"));
        dataSource.setPassword(configMap.get("password"));
        threadLocal.set(dataSource);
    }

    private static void startListener(){
        zkClient.subscribeDataChanges(config_path + "/url", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                changePool();
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                changePool();
            }
        });
    }

    private static void changePool() throws PropertyVetoException {
        if(threadLocal.get()!=null){
            threadLocal.get().close();
        }
        getConfig();
        initDataSource();
        System.out.println("更新连接池"+threadLocal.get().getJdbcUrl());
    }
}
